package com.quanyan.user.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.encrypt.Coder;
import com.quanyan.common.enums.LarkAppIdEnum;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.user.AppUserCacheInfo;
import com.quanyan.common.utils.DataEncryptionUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.GsonUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.user.cache.MyRedisTemplate;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.TbAppPromotionChannelMapper;
import com.quanyan.user.mapper.TbUserMapper;
import com.quanyan.user.model.db.*;
import com.quanyan.user.model.vo.request.*;
import com.quanyan.user.model.vo.response.*;
import com.quanyan.user.service.*;
import com.quanyan.user.utils.LarkCodeUtil;
import com.quanyan.user.utils.ValidUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 用户登陆注册
 * Created by zhang on 16/11/11.
 */
@Service
public class UserLoginServiceImpl extends UserBaseServiceImpl implements UserLoginService {
    private final static Logger logger = LoggerFactory.getLogger(UserLoginServiceImpl.class);

    private  final ExecutorService threadPool = Executors.newFixedThreadPool(2*Runtime.getRuntime().availableProcessors());
    @Autowired
    private MyRedisTemplate myRedisTemplate;
    @Autowired
    private UserInformationService userInformationService;
    @Autowired
    private TbUserMapper userMapper;
    @Autowired
    private UserToCService userToCService;
    @Autowired
    private UserIMService userIMService;
    @Autowired
    private UserSmsService userSmsService;
    @Autowired
    private HttpClientService httpClientService;

    @Value("${huanxin.nickname.prefix}")
    private String nicknamePrefix;
    @Value("${user_default_icon}")
    private String userDefaultIcon;
    @Value("${user_default_sign}")
    private String userDefaultSign;

    @Autowired
    private TbAppPromotionChannelMapper appPromotionChannelMapper;

    /**
     * 获取验证码
     *
     * @param mobile 手机号
     * @return true or false
     */
    @Override
    public APIResponse getValidCode(String mobile) {

        List<String> mobiles = new ArrayList<>();
        mobiles.add(mobile);
        APIResponse response = userSmsService.sendSms(mobiles, 1, 1, new ArrayList<String>());
        if (response != null && response.isRet() && response.getErrcode() == 200) {
            return APIResponse.returnSuccess();
        } else {
            logger.info("验证码发送失败手机号：【{}】，失败原因：【{}】",mobile,response.getErrmsg());
            return APIResponse.returnFail(response.getErrmsg());
        }
    }

    /**
     * 用户注册
     *
     * @param reqUserRegister 注册请求信息
     * @return RespUserLogin 登陆成功返回信息
     */
    @Override
    public APIResponse<RespUserLogin> verifyRegister(ReqUserRegister reqUserRegister) {
        String phone = reqUserRegister.getMobile();
        String validCode = reqUserRegister.getValidCode();
        String password = reqUserRegister.getPassword();
        String devToken = reqUserRegister.getDevToken();
        String clientId = reqUserRegister.getClientId();
        int devType = reqUserRegister.getDevType();
        String idfa = reqUserRegister.getIdfa();
        logger.info("传入的IDFA:{},传入的用户为:{}",idfa,phone);
        byte isNewUser = 0;
        APIResponse response = userSmsService.checkCode(validCode,phone);
        if (response.isRet() && response.getErrcode() != 200) {
            return APIResponse.returnFail(ApiResponseEnum.VALIDATE_CODE_ERROR);
        }
        RespUserLogin respUserLogin;
        TbUser user;
        user = getUserToDbByPhone(phone);
        if (null != user) {     //用户已经存在了
            respUserLogin = commonLogin(reqUserRegister.getUserCookiesName(),user,isNewUser,devToken,clientId,devType,"1");
            return APIResponse.returnSuccess(respUserLogin);
        }
        //用户不存在
        user = commonRegister(phone,password,reqUserRegister.getAppChannel(),Constants.RegType.REG_MOBILE,LarkCodeUtil.generateDefaultNickName(phone),null,(byte)0,idfa);
        if (user == null) {
            return APIResponse.returnFail(ApiResponseEnum.USER_IS_NULL);
        }
        isNewUser = 1;
        updateLoginInfo(devToken,clientId,user.getId());
        respUserLogin = commonLogin(reqUserRegister.getUserCookiesName(),user,isNewUser,devToken,clientId,devType,"1");
        return APIResponse.returnSuccess(respUserLogin);
    }

    /**
     * 用户登录
     *
     * @param reqUserLogin  用户登陆信息
     * @return  RespUserLogin 登陆成功返回信息
     */
    @Override
    public APIResponse<RespUserLogin> login(ReqUserLogin reqUserLogin) {
        byte type = reqUserLogin.getType();
        String phone = reqUserLogin.getPhone();
        if ((type == 1 || type == 5 || type == 6 )&& StringUtils.isBlank(phone)) {
            return APIResponse.returnFail("传入必要参数：PH");
        }
        String validCode = reqUserLogin.getValidCode();
        String reqPassword = reqUserLogin.getPassword();
        String devToken = reqUserLogin.getDevToken();
        String clientId = reqUserLogin.getClientId();
        int devType = reqUserLogin.getDevType();
        String idfa = reqUserLogin.getIdfa();
        int larkAppId = reqUserLogin.getLarkAppId();
        boolean isEnabled = isEnabled(reqUserLogin);
        if (!isEnabled) {
            return APIResponse.returnFail("账号已禁用，请联系百灵鸟客服");
        }
        TbUser user;
        byte isNewUser = 0;
        switch(type){
            case 1 :    //手机号码与密码登录
                user = getUserToDbByPhone(phone);
                if (user != null) {
                    String userPassword = user.getPassword();
                    if (reqPassword == null || userPassword == null){
                        return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_OR_PASSWORD_ERROR);
                    }
                    if (!reqPassword.toUpperCase().equals(userPassword.toUpperCase())){
                        return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_OR_PASSWORD_ERROR);
                    }
                }
                break;
            case 2 :    //微信登录
                String wechatUnionId = reqUserLogin.getWechatUnionid();
                List<TbUserAccountRelation> userAccountRelationList = getUserAccountList(larkAppId, wechatUnionId, UserConstants.AccountType.WECHAT_UNION_ID_TYPE);
                if (userAccountRelationList.isEmpty()) {
                    return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_BINDING_USER_NULL);
                } else {
                    user = getUserToDbByUid(userAccountRelationList.get(0).getUid());
                }
                break;
            case 3 :    //QQ登录
                String qqOpenId = reqUserLogin.getOpenid();
                user = getUserToDb(null,qqOpenId,null,null,null);
                break;
            case 4 :    //微博登陆
                String weiboOpenId = reqUserLogin.getOpenid();
                user = getUserToDb(null,null,weiboOpenId,null,null);
                break;
            case 5 :    //手机号验证码登陆
                APIResponse response = userSmsService.checkCode(validCode,phone);
                if (response.isRet() && response.getErrcode() != 200) {
                    return APIResponse.returnFail(ApiResponseEnum.VALIDATE_CODE_ERROR);
                }
                user = getUserToDb(phone,null,null,null,null);
                if (user == null) {
                    user = commonRegister(phone,null,reqUserLogin.getAppChannel(),Constants.RegType.REG_MOBILE,LarkCodeUtil.generateDefaultNickName(phone),null,(byte)0,idfa);
                    isNewUser = 1;
                }
                break;
            case 6 :    //通过验证码设置密码并登陆
                APIResponse responseTwo = userSmsService.checkCode(validCode,phone);
                if (responseTwo.isRet() && responseTwo.getErrcode() != 200) {
                    return APIResponse.returnFail(ApiResponseEnum.VALIDATE_CODE_ERROR);
                }
                user = getUserToDbByPhone(phone);
                if (user != null &&
                    StringUtils.isBlank(user.getPassword()) &&
                    StringUtils.isNotBlank(reqPassword)) {

                    TbUser u = new TbUser();
                    u.setId(user.getId());
                    u.setPassword(reqPassword);

                    int n = userMapper.updateByPrimaryKeySelective(u);
                    if(n <= 0){
                        return APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
                    }
                }
                break;
            default:
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        if (user == null) {
            return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_BINDING_USER_NULL);
        }
        RespUserLogin respUserLogin = commonLogin(reqUserLogin.getUserCookiesName(),user,isNewUser,devToken,clientId,devType,"1");
        return APIResponse.returnSuccess(respUserLogin);

    }


    /**
     * 用户登录时 验证用户账号是否可用
     *
     * @param reqUserLogin
     * @return
     */
    private boolean isEnabled(ReqUserLogin reqUserLogin){
        Byte type = reqUserLogin.getType();
        String phone = reqUserLogin.getPhone();
        if ((type == 1 || type == 6) && StringUtils.isNotBlank(phone) ) {
            TbUserExample userExample = new TbUserExample();
            TbUserExample.Criteria userExampleCriteria = userExample.createCriteria();
            userExampleCriteria.andMobileEqualTo(phone);
            userExampleCriteria.andIsEnableEqualTo((byte)1);
            List<TbUser> users = userMapper.selectByExample(userExample);
            if (users != null && users.size() > 0){
                return true;
            }
        }

        if (type == 5 ) {
            return true;
        }
        //第三方登录
        TbUser user = null;
        if (type == 2) {
            String wechatUnionId = reqUserLogin.getWechatUnionid();
            user = getUserToDb(null,null,null,null,wechatUnionId);
        }else if (type == 3) {
            String qqOpenId = reqUserLogin.getOpenid();
            user = getUserToDb(null,qqOpenId,null,null,null);
        }else if (type == 4) {
            String weiboOpenId = reqUserLogin.getOpenid();
            user = getUserToDb(null,null,weiboOpenId,null,null);
        }

        if ( user != null) {
            return  userInformationService.isUserEnable(user.getId());
        }
        return false;
    }

    /**
     * 初始化用户cookies
     * @param appUserCacheInfo  用户初始化信息
     * @return RespUserCookiesName
     */
    @Override
    public RespUserCookiesName appInit(AppUserCacheInfo appUserCacheInfo) {
        appUserCacheInfo.setUpdate_time(DateUtils.getSecondTimestampOne(new Date()));
        String appid = appUserCacheInfo.getAppid();
        if (StringUtils.isBlank(appid)) {
            appUserCacheInfo.setAppid("1");
            appid = "1";
        }
        String json = GsonUtils.toJson(appUserCacheInfo);
        String cookies = DataEncryptionUtils.SHA1(json);
        myRedisTemplate.setJsonToRedis(cookies,json);
        int uid = appUserCacheInfo.getUser_id();

        String userCookiesName = commonCookies(cookies,uid,appid);

        RespUserCookiesName respUserCookiesName = new RespUserCookiesName();
        respUserCookiesName.setUserCookiesName(userCookiesName);
        respUserCookiesName.setUid(uid);
        return respUserCookiesName;
    }

    /**
     * 手机号验证
     * @param reqUserSecurity 手机号 和 验证类型
     * @return RespUserSecurity 验证信息返回对象
     */
    @Override
    public APIResponse<RespUserSecurity> validateMobile(ReqUserSecurity reqUserSecurity) {
        String phone = reqUserSecurity.getPhone();
        int thirdType = reqUserSecurity.getThirdType();
        int larkAppId = reqUserSecurity.getLarkAppId();
        TbUser user = this.getUserToDbByPhone(phone);
        RespUserSecurity respUserSecurity = new RespUserSecurity();
        if (user == null) {
            //未注册
            respUserSecurity.setLevel(0);
            respUserSecurity.setDesc("该手机号未注册");
            respUserSecurity.setThirdBinding(0);
        } else {
            if (thirdType > 0) {
                switch (thirdType) {
                    case 1:    //微信
                        List<TbUserThirdAccount> userThirdAccountList = getUserThirdAccountList(user.getId(), larkAppId,null,null, UserConstants.WECHAT_TYPE);
//                        if (StringUtils.isNotBlank(user.getWeixinUnionid())) {
//                            respUserSecurity.setThirdBinding(1);
//                        } else {
//                            respUserSecurity.setThirdBinding(0);
//                        }
                        if (userThirdAccountList.isEmpty()) {
                            respUserSecurity.setThirdBinding(0);
                        } else {
                            respUserSecurity.setThirdBinding(1);
                        }
                        break;
                    case 2:    //QQ
                        if (StringUtils.isNotBlank(user.getQqOpenid())) {
                            respUserSecurity.setThirdBinding(1);
                        } else {
                            respUserSecurity.setThirdBinding(0);
                        }
                        break;
                    case 3:    //微博
                        if (StringUtils.isNotBlank(user.getWeiboOpenid())) {
                            respUserSecurity.setThirdBinding(1);
                        } else {
                            respUserSecurity.setThirdBinding(0);
                        }
                        break;
                }
            }

            String pwd = user.getPassword();
            Date createTime = user.getCreateTime();
            if (StringUtils.isBlank(pwd)) {
                //无密码
                respUserSecurity.setLevel(1);
                respUserSecurity.setDesc("该手机号已注册");
                if (null != createTime) {
                    respUserSecurity.setCreateTime(createTime.getTime());
                }
            } else {
                //有密码
                respUserSecurity.setLevel(2);
                respUserSecurity.setDesc("该手机号已注册");
                if (null != createTime) {
                    respUserSecurity.setCreateTime(createTime.getTime());
                }
            }
        }
        return APIResponse.returnSuccess(respUserSecurity);
    }

    /**
     * 修改密码
     * @param reqUserChangePassword 用户修改密码对象
     * @return true or false
     */
    @Override
    public APIResponse changePassword(ReqUserChangePassword reqUserChangePassword) {
        int type = reqUserChangePassword.getType();
        String phone = reqUserChangePassword.getPhone();
        String newPassword = reqUserChangePassword.getNewPassword();
        TbUser user = this.getUserToDbByPhone(phone);
        if (null == user) {
            return APIResponse.returnFail(ApiResponseEnum.USER_IS_NULL);
        }
        if (type == 1) {    //通过旧密码来修改密码
            String password = user.getPassword();
            String oldPassword = reqUserChangePassword.getOldPassword();
            if (null == oldPassword || password == null) {
                return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_OR_PASSWORD_ERROR);
            }
            if (oldPassword.toUpperCase().equals(password.toUpperCase())) {
                TbUser newUser = new TbUser();
                newUser.setPassword(newPassword);
                int n = userInformationService.updateUser(newUser,user.getId());
                if (n > 0) {
                    return APIResponse.returnSuccess();
                } else {
                    return APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
                }
            } else {
                return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_OR_PASSWORD_ERROR);
            }
        }
        if (type == 2) {    //通过校验验证码来修改密码
            String validCode = reqUserChangePassword.getValidCode();
            if (null == validCode) {
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
            }
            APIResponse response = userSmsService.checkCode(validCode,phone);

            if (response.isRet() && response.getErrcode() == 200) {
                TbUser newUser = new TbUser();
                newUser.setPassword(newPassword);
                int n = userInformationService.updateUser(newUser,user.getId());
                if (n > 0) {
                    return APIResponse.returnSuccess();
                } else {
                    return APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
                }
            } else {
                return APIResponse.returnFail(ApiResponseEnum.VALIDATE_CODE_ERROR);
            }
        }
        if (type == 3) {    //校验用户密码是否为null并设置密码
            String password = user.getPassword();
            if (null == password) {
                TbUser newUser = new TbUser();
                newUser.setPassword(newPassword);
                int n = userInformationService.updateUser(newUser,user.getId());
                if (n > 0) {
                    return APIResponse.returnSuccess();
                } else {
                    return APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
                }
            } else {
                return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_OR_PASSWORD_ERROR);
            }
        }
        return APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
    }

    /**
     * 验证密码
     * @param uid 用户id
     * @param password 用户密码
     * @return true or false
     */
    @Override
    public APIResponse verifyPassword(int uid, String password) {
        TbUser user = this.getUserToDbByUid(uid);

        if (user != null && user.getPassword() != null && password.toUpperCase().equals(user.getPassword().toUpperCase())) {

            return APIResponse.returnSuccess();
        }
        return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_OR_PASSWORD_ERROR);
    }

    /**
     * 获取用户
     * @param reqGetUser 获取用户请求对象
     * @return RespUserCookiesName 用户cookies信息
     */
    @Override
    public APIResponse<RespUserCookiesName> getUser(ReqGetUser reqGetUser) {
        int type = reqGetUser.getType();
        int larkAppId = reqGetUser.getLarkAppId();
        int uid;
        if (type == 1 && reqGetUser.getOpenId() == null) {
            return APIResponse.returnFail("缺少TypeOne必要参数！");
        }
        if (type == 2 && reqGetUser.getUnionId() == null) {
            return APIResponse.returnFail("缺少TypeTwo必要参数！！");
        }
        if (type == 3 && reqGetUser.getPhone() == null) {
            return APIResponse.returnFail("缺少TypeThree必要参数！！!");
        }
        if (type == 4 && reqGetUser.getPhone() == null && reqGetUser.getValidCode() == null) {
            return APIResponse.returnFail("缺少TypeFour必要参数！！！！");
        }
        RespUserCookiesName respUserCookiesName = new RespUserCookiesName();
        TbUser user = null;
        if (type == 1) {    //openId获取用户信息
//            TbUserAccountRelation userAccountRelation = this.getUserAccountRelation(type,reqGetUser.getOpenId(),reqGetUser.getUnionId());
//            if (userAccountRelation == null) {
//                respUserCookiesName.setUid(0);
//                respUserCookiesName.setUserCookiesName("");
//                return APIResponse.returnSuccess(respUserCookiesName);
//            }

            List<TbUserThirdAccount> userThirdAccountList = getUserThirdAccountList(null, larkAppId, null, reqGetUser.getOpenId(), UserConstants.WECHAT_TYPE);
            if (userThirdAccountList.isEmpty()) {
                respUserCookiesName.setUid(0);
                respUserCookiesName.setUserCookiesName("");
                return APIResponse.returnSuccess(respUserCookiesName);
            }
            uid = userThirdAccountList.get(0).getUid();
        } else if(type == 2) {  //unionId获取用户信息
            List<TbUserThirdAccount> userThirdAccountList = getUserThirdAccountList(null, larkAppId, reqGetUser.getUnionId(), null, UserConstants.WECHAT_TYPE);
            if (userThirdAccountList.isEmpty()) {
                respUserCookiesName.setUid(0);
                respUserCookiesName.setUserCookiesName("");
                return APIResponse.returnSuccess(respUserCookiesName);
            }
            uid = userThirdAccountList.get(0).getUid();
        } else if(type == 3) {  //phone获取用户信息
            user = this.getUserToDb(reqGetUser.getPhone(),null,null,null,null);
            if (user == null) {
                respUserCookiesName.setUid(0);
                respUserCookiesName.setUserCookiesName("");
                return APIResponse.returnSuccess(respUserCookiesName);
            }
            uid = user.getId();
        } else if(type == 4) {  //通过手机和验证码（提供自动注册机制）
            String phone = reqGetUser.getPhone();
            String validCode = reqGetUser.getValidCode();
            APIResponse response = userSmsService.checkCode(validCode,phone);
            if (response.isRet() && response.getErrcode() != 200) {
                return APIResponse.returnFail(ApiResponseEnum.VALIDATE_CODE_ERROR);
            }
            user = this.getUserToDb(reqGetUser.getPhone(),null,null,null,null);
            if (user == null) {
                user = commonRegister(phone,null,null,Constants.RegType.REG_H5,LarkCodeUtil.generateDefaultNickName(phone),null,(byte)0,null);
            }
            if (user == null) {
                return APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
            } else {
                uid = user.getId();
            }
        } else {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        if (type == 1 || type == 2) {
            user = getUserToDbByUid(uid);
        }
        if (user == null) {
            respUserCookiesName.setUid(0);
            respUserCookiesName.setUserCookiesName("");
            return APIResponse.returnSuccess(respUserCookiesName);
        }
        respUserCookiesName.setNickName(user.getNickName());
        respUserCookiesName.setPhone(user.getMobile());
        respUserCookiesName.setGender(user.getGender());
        respUserCookiesName.setUid(uid);
        //判断用户是否存在环信账号
        TbImDetails imDetails = getImDetails(uid);
        if (null == imDetails) {
            userIMService.addImDetails(nicknamePrefix + uid, DataEncryptionUtils.SHA1(String.valueOf(uid)), uid);
        }
        String userCookiesName = commonCookies(null,uid,"1");
        respUserCookiesName.setUserCookiesName(userCookiesName);

        return APIResponse.returnSuccess(respUserCookiesName);
    }

    /**
     * 用户账户绑定
     * @param reqUserBinding 用户微信绑定信息
     * @return RespUserCookiesName 用户cookies及相关信息
     */
    @Override
    public APIResponse<RespUserCookiesName> userBinding(ReqUserBinding reqUserBinding) {
        RespUserCookiesName respUserCookiesName = new RespUserCookiesName();
        String phone = reqUserBinding.getPhone();
        String openId = reqUserBinding.getOpenId();
        String unionId = reqUserBinding.getUnionId();
        int larkAppId = reqUserBinding.getLarkAppId();
        String thirdNickname = reqUserBinding.getThirdNickname();
        if (StringUtils.isBlank(thirdNickname)) {
            return APIResponse.returnFail("缺少必要参数--N");
        }
        String thirdIcon = reqUserBinding.getThirdIcon();
        if (StringUtils.isBlank(thirdIcon)) {
            thirdIcon = userDefaultIcon;
        }
        //去除手机号中的空格
        phone = StringUtil.replaceBlank(phone);
        //校验手机格式
        if (!ValidUtils.isRegMobile(phone)) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        if (StringUtils.isBlank(openId)) {
            return APIResponse.returnFail("缺少必要参数--O");
        }
        int type = reqUserBinding.getType();
        boolean flag = false;
        switch (type){
            case 1 :    //验证验证码
                APIResponse response = userSmsService.checkCode(reqUserBinding.getValidCode(),phone);

                if (response.isRet() && response.getErrcode() == 200) {
                    flag = true;
                } else {
                    return APIResponse.returnFail(ApiResponseEnum.VALIDATE_CODE_ERROR);
                }
                break;
            case 2 :    //不验证验证码
                flag = true;
                break;
        }
        if (flag && type == 1) {

            int isNewUser = 0;
            //查看该unionId是否已被绑定
//            TbUser valid = this.getUserToDb(null,null,null,null,unionId);
            List<TbUserThirdAccount> userThirdAccountList = getUserThirdAccountList(null, larkAppId, unionId, null, UserConstants.WECHAT_TYPE);
            TbUser valid = null;
            if (!userThirdAccountList.isEmpty()) {
                valid = getUserToDbByUid(userThirdAccountList.get(0).getUid());
            }
            if (valid == null) {
                TbUser user = this.getUserToDbByPhone(phone);
                int uid;
                if (null == user) { //对用户进行注册
                    TbUser tbUser = new TbUser();
                    tbUser.setMobile(phone);
                    tbUser.setNickName(thirdNickname);
                    tbUser.setIcon(thirdIcon);
                    tbUser.setGender(reqUserBinding.getThirdGender());
                    tbUser.setRegTime(new Date());
                    tbUser.setRegType(Constants.RegType.REG_H5);
                    if (larkAppId == LarkAppIdEnum.LARK_APP_C.getId()) {
                        tbUser.setWeixinNickname(thirdNickname);
                        tbUser.setWeixinAppIconUrl(thirdIcon);
                        tbUser.setWeixinUnionid(unionId);
                        tbUser.setWeixinAppOpenid(openId);
                    }
                    int n = userMapper.insertSelective(tbUser);
                    uid = tbUser.getId();
                    if (n>0 && uid >0) {
//                        isNewUser = 1;
                        TbUser u = new TbUser();
                        u.setLarkCode(LarkCodeUtil.generateLarkCode(uid));
                        u.setId(uid);
                        userMapper.updateByPrimaryKeySelective(u);

                        Map<String,Integer> map = new HashMap();
                        map.put("currentUid",uid);
                        userToCService.initUserInfo(map);
                        user = getUserToDbByUid(uid);
                    } else {
                        return APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
                    }
                }
                uid = user.getId();
                //删除以前绑定的opendId
//                updateUserAccountRelation(uid,null);
                deleteUserThirdAccount(uid, larkAppId, UserConstants.WECHAT_TYPE);

                respUserCookiesName.setNickName(user.getNickName());
                respUserCookiesName.setPhone(user.getMobile());
                respUserCookiesName.setGender(user.getGender());

//                TbUserAccountRelation userAccountRelationOpen = this.getUserAccountRelation(1,openId,null);
//                if (userAccountRelationOpen == null) {
//                    if (StringUtils.isNotBlank(openId)) {
//                        addUserAccountRelation(1,openId,null,uid);
//                    }
//                }
                TbUserThirdAccount userThirdAccount = new TbUserThirdAccount();
                userThirdAccount.setUid(uid);
                userThirdAccount.setThirdNickname(thirdNickname);
                userThirdAccount.setThirdIcon(thirdIcon);
                userThirdAccount.setOpenId(openId);
                userThirdAccount.setUnionId(unionId);
                userThirdAccount.setLarkAppId(larkAppId);
                userThirdAccount.setThirdGender((byte)0);
                userThirdAccount.setType(UserConstants.WECHAT_TYPE);
                int n = insertUserThirdAccount(userThirdAccount);
//                if (isNewUser == 0 && type == 1) {
//                    TbUser u = new TbUser();
//                    u.setId(uid);
//                    u.setWeixinAppOpenid(openId);
//                    u.setWeixinUnionid(unionId);
//                    u.setWeixinNickname(thirdNickname);
//                    u.setWeixinAppIconUrl(thirdIcon);
//                    userMapper.updateByPrimaryKeySelective(u);
//                }

                respUserCookiesName.setUid(uid);
                //判断用户是否存在环信账号
                TbImDetails imDetails = getImDetails(uid);
                if (null == imDetails) {
                    userIMService.addImDetails(nicknamePrefix + uid, DataEncryptionUtils.SHA1(String.valueOf(uid)), uid);
                }
                String userCookiesName = commonCookies(null,uid,"0");
                respUserCookiesName.setUserCookiesName(userCookiesName);
            } else {
                return APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
            }

        } else if(flag && type == 2) {
            TbUser user = getUserToDb(phone,null,null,null,unionId);
            int uid;
            if (user != null) {
                uid = user.getId();
            } else {
                return APIResponse.returnFail(ApiResponseEnum.USER_IS_NULL);
            }

//            TbUserAccountRelation userAccountRelationOpen = this.getUserAccountRelation(1,openId,null);
//            if (userAccountRelationOpen == null) {
//                addUserAccountRelation(1,openId,null,uid);
//            } else {
//                updateUserAccountRelation(userAccountRelationOpen.getUid(), openId);
//
//                addUserAccountRelation(1,openId,null,uid);
//            }
            List<TbUserThirdAccount> userThirdAccountList = getUserThirdAccountList(null, larkAppId, null, openId, UserConstants.WECHAT_TYPE);
            if (userThirdAccountList.isEmpty()) {
                TbUserThirdAccount userThirdAccount = new TbUserThirdAccount();
                userThirdAccount.setLarkAppId(larkAppId);
                userThirdAccount.setOpenId(openId);
                userThirdAccount.setUnionId(unionId);
                userThirdAccount.setThirdGender((byte)0);
                userThirdAccount.setThirdIcon(thirdIcon);
                userThirdAccount.setThirdNickname(thirdNickname);
                userThirdAccount.setType(UserConstants.WECHAT_TYPE);
                insertUserThirdAccount(userThirdAccount);
            } else {
                deleteUserThirdAccount(uid, larkAppId, UserConstants.WECHAT_TYPE);
            }

            respUserCookiesName.setNickName(user.getNickName());
            respUserCookiesName.setPhone(user.getMobile());
            respUserCookiesName.setGender(user.getGender());
            respUserCookiesName.setUid(user.getId());
        } else {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        return APIResponse.returnSuccess(respUserCookiesName);
    }

    /**
     * 验证、绑定、解绑第三方账号
     * @param reqUserLogin 登陆对象
     * @return APIResponse
     */
    @Override
    public APIResponse validBindingThirdAccount(ReqUserLogin reqUserLogin) {
        int operateType = reqUserLogin.getOperateType();
        int type = reqUserLogin.getType();
        String appChannel = reqUserLogin.getAppChannel();
        String userCookiesName = reqUserLogin.getUserCookiesName();
        String openId = reqUserLogin.getOpenid();
        String unionId = reqUserLogin.getWechatUnionid();
        String devToken = reqUserLogin.getDevToken();
        String clientId = reqUserLogin.getClientId();
        int devType = reqUserLogin.getDevType();
        String idfa = reqUserLogin.getIdfa();
        int larkAppId = reqUserLogin.getLarkAppId();
        TbUser user = null;
        byte isNewUser = 0;
        int uid ;
        byte regType = 0;
        RespUserLogin respUserLogin;
        switch (operateType){
            case 1 :    //验证
                if(type == 2) {      //微信
                    List<TbUserThirdAccount> userThirdAccountList = getUserThirdAccountList(null, larkAppId, unionId, null, UserConstants.WECHAT_TYPE);
                    if (userThirdAccountList.isEmpty()) {
                        return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_NOT_BINDING);
                    } else {
                        TbUserThirdAccount userThirdAccount = userThirdAccountList.get(0);
                        user = getUserToDbByUid(userThirdAccount.getUid());
                    }
//                    user = getUserToDb(null, null, null, null, unionId);
                }
                if (type == 3) {    //QQ
                    user = getUserToDb(null,openId,null,null,null);
                }
                if (type == 4) {    //微博
                    user = getUserToDb(null,null,openId,null,null);
                }
                if (user != null) {
                    respUserLogin = commonLogin(userCookiesName,user,isNewUser,devToken,clientId,devType,"1");
                    return APIResponse.returnSuccess(respUserLogin);
                } else {
                    return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_NOT_BINDING);
                }
            case 2 :    //绑定
                int n = 0;
                String validCode = reqUserLogin.getValidCode();
                String phone = reqUserLogin.getPhone();
                APIResponse response = userSmsService.checkCode(validCode,phone);
                if (response.isRet() && response.getErrcode() == 200) {
                    TbUser userBind = null;
                    if (type == 1) {
                        regType = Constants.RegType.REG_MOBILE;
                    } else if (type == 2) {
                        regType = Constants.RegType.REG_WECHAT;

                        List<TbUserThirdAccount> userThirdAccountList = getUserThirdAccountList(null, larkAppId, unionId, null, UserConstants.WECHAT_TYPE);
                        if (!userThirdAccountList.isEmpty()) {
//                            return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_NOT_BINDING);
                            TbUserThirdAccount userThirdAccount = userThirdAccountList.get(0);
                            userBind = getUserToDbByUid(userThirdAccount.getUid());
                        }

//                        userBind = getUserToDb(null,null,null,null,unionId);
                    } else if (type == 3) {
                        regType = Constants.RegType.REG_QQ;
                        userBind = getUserToDb(null,openId,null,null,null);
                    } else if (type == 4) {
                        regType = Constants.RegType.REG_WEIBO;
                        userBind = getUserToDb(null,null,openId,null,null);
                    }
                    if (userBind != null) {
                        return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_HAD_BINDING);
                    }
                    user = getUserToDb(phone,null,null,null,null);
                    if( user == null){
                        TbUser u = commonRegister(phone,null,appChannel,regType,reqUserLogin.getThirdNickname(),reqUserLogin.getThirdIcon(),reqUserLogin.getThirdGender(),idfa);
                        if (u == null) {
                            return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_BINDING_FAIL);
                        } else {
                            isNewUser = 1;
                            user = getUserToDb(phone,null,null,null,null);
                        }
                    }
                        TbUser u = new TbUser();
                        uid = user.getId();
                        //解除该用户与其它openId的绑定关系
                        if(type == 2) {
//                            updateUserAccountRelation(uid,null);
                            deleteUserThirdAccount(uid, larkAppId, UserConstants.WECHAT_TYPE);
                        }

                        u.setId(uid);
                        if(type == 2){  //微信
                            if (larkAppId == LarkAppIdEnum.LARK_APP_C.getId()) {
                                u.setWeixinAppOpenid(reqUserLogin.getOpenid());
                                u.setWeixinUnionid(reqUserLogin.getWechatUnionid());
                                u.setWeixinAppIconUrl(reqUserLogin.getThirdIcon());
                                u.setWeixinNickname(reqUserLogin.getThirdNickname());
                            }
                            TbUserThirdAccount userThirdAccount = new TbUserThirdAccount();
                            userThirdAccount.setUid(uid);
                            userThirdAccount.setLarkAppId(larkAppId);
                            userThirdAccount.setOpenId(openId);
                            userThirdAccount.setUnionId(unionId);
                            userThirdAccount.setThirdGender((byte)0);
                            userThirdAccount.setThirdIcon(reqUserLogin.getThirdIcon());
                            userThirdAccount.setThirdNickname(reqUserLogin.getThirdNickname());
                            userThirdAccount.setType(UserConstants.WECHAT_TYPE);
                            n = insertUserThirdAccount(userThirdAccount);
                        }
                        if (type == 3) {    //QQ
                            u.setQqOpenid(reqUserLogin.getOpenid());
                            u.setQqIconUrl(reqUserLogin.getThirdIcon());
                            u.setQqNickname(reqUserLogin.getThirdNickname());
                            n = userMapper.updateByPrimaryKeySelective(u);
                        }
                        if (type == 4) {    //微博
                            u.setWeiboOpenid(reqUserLogin.getOpenid());
                            u.setWeiboIconUrl(reqUserLogin.getThirdIcon());
                            u.setWeiboNickname(reqUserLogin.getThirdNickname());
                            n = userMapper.updateByPrimaryKeySelective(u);
                        }

                        if(n > 0){
//                            if (type == 2) {
//                                TbUserAccountRelation userAccountRelationOpen = this.getUserAccountRelation(1,openId,null);
//                                if (userAccountRelationOpen == null) {
//                                    if (StringUtils.isNotBlank(openId)) {
//                                        addUserAccountRelation(1,openId,null,uid);
//                                    }
//                                }
//                            }
                            user = getUserToDbByUid(uid);
                            respUserLogin = commonLogin(userCookiesName,user,isNewUser,devToken,clientId,devType,"1");
                            return APIResponse.returnSuccess(respUserLogin);
                        } else {
                            return APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
                        }
                } else {
                    return APIResponse.returnFail(ApiResponseEnum.VALIDATE_CODE_ERROR);
                }
            case 3 :    //解绑
                int k = 0;
                uid = reqUserLogin.getUid();
                user = getUserToDbByUid(uid);
                if (user != null) {
                    if(type == 2) {  //微信
                        if (larkAppId == LarkAppIdEnum.LARK_APP_C.getId()) {
                            user.setWeixinAppOpenid(null);
                            user.setWeixinUnionid(null);
                            user.setWeixinAppIconUrl(null);
                            user.setWeixinNickname(null);
                            userMapper.updateByPrimaryKey(user);
                        }
                        k = deleteUserThirdAccount(uid, larkAppId, UserConstants.WECHAT_TYPE);
                    }
                    if (type == 3) {    //QQ
                        user.setQqOpenid(null);
                        user.setQqIconUrl(null);
                        user.setQqNickname(null);
                        k = userMapper.updateByPrimaryKey(user);
                    }
                    if (type == 4) {    //微博
                        user.setWeiboOpenid(null);
                        user.setWeiboIconUrl(null);
                        user.setWeiboNickname(null);
                        k = userMapper.updateByPrimaryKey(user);
                    }

                    if (k > 0) {
//                        if(type == 2){
//                            updateUserAccountRelation(uid,null);
//                        }
                        return APIResponse.returnSuccess();
                    } else {
                        return APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
                    }
                } else {
                    return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_BINDING_USER_NULL);
                }

            case 4 :    //app内部绑定
                int m = 0;
                uid = reqUserLogin.getUid();
                user = getUserToDbByUid(uid);
                if (user == null) {
                    return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_BINDING_USER_NULL);
                }
                TbUser bindUser = null;
                if(type == 2){      //微信
                    List<TbUserThirdAccount> userThirdAccountList = getUserThirdAccountList(null, larkAppId, unionId, null, UserConstants.WECHAT_TYPE);
                    if (!userThirdAccountList.isEmpty()) {
//                        return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_NOT_BINDING);
                        TbUserThirdAccount userThirdAccount = userThirdAccountList.get(0);
                        bindUser = getUserToDbByUid(userThirdAccount.getUid());
                    }
//                    bindUser = getUserToDb(null,null,null,null,unionId);
                }
                if (type == 3) {    //QQ
                    bindUser = getUserToDb(null,openId,null,null,null);
                }
                if (type == 4) {    //微博
                    bindUser = getUserToDb(null,null,openId,null,null);
                }
                if(bindUser != null){
                    return APIResponse.returnFail(ApiResponseEnum.ACCOUNT_HAD_BINDING);
                }
                TbUser u = new TbUser();
                uid = user.getId();
                u.setId(uid);
                if(type == 2){  //微信
                    if (larkAppId == LarkAppIdEnum.LARK_APP_C.getId()) {
                        u.setWeixinAppOpenid(reqUserLogin.getOpenid());
                        u.setWeixinUnionid(reqUserLogin.getWechatUnionid());
                        u.setWeixinAppIconUrl(reqUserLogin.getThirdIcon());
                        u.setWeixinNickname(reqUserLogin.getThirdNickname());
                        userMapper.updateByPrimaryKeySelective(u);

                    }
                    TbUserThirdAccount userThirdAccount = new TbUserThirdAccount();
                    userThirdAccount.setUid(uid);
                    userThirdAccount.setLarkAppId(larkAppId);
                    userThirdAccount.setOpenId(openId);
                    userThirdAccount.setUnionId(unionId);
                    userThirdAccount.setThirdGender((byte)0);
                    userThirdAccount.setThirdIcon(reqUserLogin.getThirdIcon());
                    userThirdAccount.setThirdNickname(reqUserLogin.getThirdNickname());
                    userThirdAccount.setType(UserConstants.WECHAT_TYPE);
                    m = insertUserThirdAccount(userThirdAccount);
                }
                if (type == 3) {    //QQ
                    u.setQqOpenid(reqUserLogin.getOpenid());
                    u.setQqIconUrl(reqUserLogin.getThirdIcon());
                    u.setQqNickname(reqUserLogin.getThirdNickname());
                    m = userMapper.updateByPrimaryKeySelective(u);
                }
                if (type == 4) {    //微博
                    u.setWeiboOpenid(reqUserLogin.getOpenid());
                    u.setWeiboIconUrl(reqUserLogin.getThirdIcon());
                    u.setWeiboNickname(reqUserLogin.getThirdNickname());
                    m = userMapper.updateByPrimaryKeySelective(u);
                }

                if(m > 0){
                    user = getUserToDbByUid(uid);
                    respUserLogin = commonLogin(userCookiesName,user,isNewUser,devToken,clientId,devType,"1");
                    return APIResponse.returnSuccess(respUserLogin);
                } else {
                    return APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR);
                }
            default:
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
    }

    /**
     * 用户cookies验证
     * @param uid 用户id
     * @return  true or false
     */
    @Override
    public APIResponse validateCookies(int uid) {
        TbUser user = getUserToDbByUid(uid);
        RespUserCookiesName respUserCookiesName = new RespUserCookiesName();
        if(user != null){
            respUserCookiesName.setPhone(user.getMobile());
            respUserCookiesName.setGender(user.getGender());
            respUserCookiesName.setNickName(user.getNickName());
            respUserCookiesName.setUid(user.getId());
        } else {
            return APIResponse.returnFail(ApiResponseEnum.USER_IS_NULL);
        }
        return APIResponse.returnSuccess(respUserCookiesName);
    }

    /**
     * 登陆公共调用
     * @param userCookiesName 用户cookies
     * @param user 用户对象
     * @param isNewUser 是否为新用户：0为不是；1为是
     * @return RespUserLogin 用户登陆返回信息
     */
    @Override
    public RespUserLogin commonLogin(String userCookiesName,TbUser user,byte isNewUser,String devToken,String clientId,int devType,String appid){
        int uid = user.getId();

        updateLoginInfo(devToken,clientId,uid);
        if (devType == 1 || devType == 2) {
            setPushCache(uid,clientId,devToken,devType,Integer.valueOf(appid));
        }

        RespUserLogin respUserLogin = new RespUserLogin();
        if (StringUtil.isBlankOrNull(user.getPassword())) {
            respUserLogin.setSecurityLev(UserConstants.SECURITY_LEVEL_LOW);
        } else {
            respUserLogin.setSecurityLev(UserConstants.SECURITY_LEVEL_HIGH);
        }
        //用户基本信息
        RespBaseUserInfo respBaseUserInfo = new RespBaseUserInfo();
        respBaseUserInfo.setUid(uid);
        respBaseUserInfo.setNickName(user.getNickName());
        respBaseUserInfo.setGender(user.getGender());
        respBaseUserInfo.setMobile(user.getMobile());
        if (user.getYear() != null) {
            respBaseUserInfo.setYear(user.getYear());
        }
        respBaseUserInfo.setIsNewuser(isNewUser);
        respBaseUserInfo.setProvinceId(user.getProvinceId());
        respBaseUserInfo.setAreaId(user.getAreaId());
        respBaseUserInfo.setAvatar(user.getIcon());
        respBaseUserInfo.setIcon(user.getIcon());
        respBaseUserInfo.setSign(user.getSign());
        respBaseUserInfo.setLarkCode(user.getLarkCode());
        respUserLogin.setRespUserEntity(respBaseUserInfo);
        //获取用户环信账号信息
        TbImDetails imDetails = getImDetails(uid);
        if (null != imDetails) {
            respUserLogin.setHuanxinUsername(imDetails.getNickName());
            respUserLogin.setHuanxinPassword(imDetails.getPassword());
        } else {
            TbImDetails tbImDetails = userIMService.addImDetails(nicknamePrefix + uid, DataEncryptionUtils.SHA1(String.valueOf(uid)), uid);
            if (tbImDetails != null && tbImDetails.getId() > 0) {
                respUserLogin.setHuanxinUsername(tbImDetails.getNickName());
                respUserLogin.setHuanxinPassword(tbImDetails.getPassword());
            } else {
                respUserLogin.setHuanxinUsername("");
                respUserLogin.setHuanxinPassword("");
            }
        }
        //获取用户客服专员
        List<TbUser> commissionerList = getCommissionerList();
        int k = commissionerList.size();
        if (k > 0) {
            TbUser com = commissionerList.get(uid%k);
            RespBaseUserInfo commissioner = new RespBaseUserInfo();
            int commissionerUid = com.getId();
            commissioner.setUid(commissionerUid);
            commissioner.setGender(com.getGender());
            commissioner.setAvatar(com.getIcon());
            commissioner.setNickName(com.getNickName());
            commissioner.setMobile(com.getMobile());

            TbImDetails im = getImDetails(commissionerUid);
            if (null != im) {
                commissioner.setHuanxinUsername(im.getNickName());
            } else {
                TbImDetails commissionerIm = userIMService.addImDetails(nicknamePrefix + commissionerUid, DataEncryptionUtils.SHA1(String.valueOf(commissionerUid)), commissionerUid);
                if (commissionerIm != null && commissionerIm.getId() > 0) {
                    commissioner.setHuanxinUsername(commissionerIm.getNickName());
                } else {
                    commissioner.setHuanxinUsername("");
                }
            }

            respUserLogin.setCommissioner(commissioner);
        }
        userCookiesName = commonCookies(userCookiesName,uid,appid);
        respUserLogin.setUserCookieName(userCookiesName);
        return respUserLogin;
    }

    /**
     * 获取用户绑定信息
     * @param uid 用户ID
    * @param larkAppId
     * @return RespUserBindingInfo 用户绑定信息
     */
    @Override
    public APIResponse<RespUserBindingInfo> bindingList(int uid, int larkAppId) {
        RespUserBindingInfo respUserBindingInfo = new RespUserBindingInfo();
        TbUser user = getUserToDbByUid(uid);
        if (user == null) {
            return APIResponse.returnFail(ApiResponseEnum.USER_IS_NULL);
        } else {
            respUserBindingInfo.setPhone(user.getMobile());
            respUserBindingInfo.setNickname(user.getNickName());
//            if (StringUtils.isBlank(user.getWeixinUnionid())) {
//                respUserBindingInfo.setWechatUnionid("");
//                respUserBindingInfo.setWechatNickname("");
//            } else {
//                respUserBindingInfo.setWechatUnionid(user.getWeixinUnionid());
//                respUserBindingInfo.setWechatNickname(user.getWeixinNickname());
//            }
            if (StringUtils.isBlank(user.getQqOpenid())) {
                respUserBindingInfo.setQqOpenid("");
                respUserBindingInfo.setQqNickname("");
            } else {
                respUserBindingInfo.setQqOpenid(user.getQqOpenid());
                respUserBindingInfo.setQqNickname(user.getQqNickname());
            }
            if (StringUtils.isBlank(user.getWeiboOpenid())) {
                respUserBindingInfo.setWeiboOpenid("");
                respUserBindingInfo.setWeiboNickname("");
            } else {
                respUserBindingInfo.setWeiboOpenid(user.getWeiboOpenid());
                respUserBindingInfo.setWeiboNickname(user.getWeiboNickname());
            }

            //微信绑定情况
            List<TbUserThirdAccount> userThirdAccountList = getUserThirdAccountList(uid, larkAppId, null, null, UserConstants.WECHAT_TYPE);
            if (userThirdAccountList.isEmpty()) {
                respUserBindingInfo.setWechatUnionid("");
                respUserBindingInfo.setWechatNickname("");
            } else {
                TbUserThirdAccount userThirdAccount = userThirdAccountList.get(0);
                respUserBindingInfo.setWechatUnionid(userThirdAccount.getUnionId());
                respUserBindingInfo.setWechatNickname(userThirdAccount.getThirdNickname());
            }
        }
        return APIResponse.returnSuccess(respUserBindingInfo);
    }

    /**
     * 退出登录
     * @param map clientId、userCookiesName、uid
     * @return RespUserCookiesName 用户cookies信息
     */
    @Override
    public APIResponse<RespUserCookiesName> logout(Map map) {
        String clientId = (String) map.get("clientId");
        int uid = (int) map.get("uid");
        String userCookiesName = (String) map.get("userCookiesName");
        //重新生成userCookiesName
        userCookiesName = commonCookies(userCookiesName,0,"1");
        if (StringUtils.isNotBlank(clientId)) {
            //删除推送信息
            StringBuffer key = new StringBuffer();
            key.append("cache_").append(uid).append("_push");
            myRedisTemplate.hdel(key.toString(),clientId.getBytes());
        }

        RespUserCookiesName respUserCookiesName = new RespUserCookiesName();
        respUserCookiesName.setUserCookiesName(userCookiesName);
        return APIResponse.returnSuccess(respUserCookiesName);
    }

    /**
     * 达人B端登录
     * @param reqDarenLogin
     * @return
     */
    @Override
    public APIResponse<RespUserLogin> darenLogin(ReqDarenLogin reqDarenLogin) {
        int type = reqDarenLogin.getType();
        String phone = reqDarenLogin.getPhone();
        if (type == 1&& StringUtils.isBlank(phone)) {
            return APIResponse.returnFail("传入必要参数：PH");
        }
        String validCode = reqDarenLogin.getValidCode();
        String devToken = reqDarenLogin.getDevToken();
        String clientId = reqDarenLogin.getClientId();
        int devType = reqDarenLogin.getDevType();
        TbUser user;
        byte isNewUser = 0;
        switch(type){
            case 1 :    //手机号验证码登陆
                APIResponse response = userSmsService.checkCode(validCode,phone);
                if (response.isRet() && response.getErrcode() != 200) {
                    return APIResponse.returnFail(ApiResponseEnum.VALIDATE_CODE_ERROR);
                }
                user = getUserToDb(phone,null,null,null,null);
                if (user == null) {
                    return APIResponse.returnFail(ApiResponseEnum.USER_IS_NULL);
                }
                break;
            default:
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        RespUserLogin respUserLogin;
        RespCheckDarenAuth respCheckDarenAuth = httpClientService.checkDarenAuth(2,phone);
        boolean ret = respCheckDarenAuth.isRet();
        int errcode = respCheckDarenAuth.getErrcode();
        String errmsg = respCheckDarenAuth.getErrmsg();
        DarenAgent agent = respCheckDarenAuth.getData().getAgent();
        if (ret && errcode == 200 && (respCheckDarenAuth.getData().isHas_auth())) {
            respUserLogin = commonLogin(reqDarenLogin.getUserCookiesName(),user,isNewUser,devToken,clientId,devType,"3");
            respUserLogin.setAgent(agent);
            return APIResponse.returnSuccess(respUserLogin);
        } else {
            respUserLogin = new RespUserLogin();
            respUserLogin.setAgent(agent);
            return APIResponse.returnSuccess(errcode, errmsg, respUserLogin);
        }
    }

    /**
     * 公用用户注册
     * @param phone 手机号
     * @param password 用密码
     * @return TbUser 用户信息
     */
    @Override
    public TbUser commonRegister(final String phone,String password,String appChannel,byte regType,String nickname,String icon,byte gender,final String idfa){
        TbUser tbUser = new TbUser();
        tbUser.setMobile(phone);
        tbUser.setAppChannel(appChannel);
        if (!StringUtils.isBlank(nickname)) {
            tbUser.setNickName(nickname);
        } else {
            tbUser.setNickName("");
        }
        if (!StringUtils.isBlank(icon)) {
            tbUser.setIcon(icon);
        }
        tbUser.setGender(gender);
        tbUser.setRegTime(new Date());
        tbUser.setRegType(regType);
        tbUser.setSign(userDefaultSign);
        if (StringUtils.isNotBlank(password)) {
            tbUser.setPassword(password);
        }
        int n = userMapper.insertSelective(tbUser);
        final int uid = tbUser.getId();
        TbUser user;
        if (n>0 && uid >0) {
            TbUser u = new TbUser();
            u.setLarkCode(LarkCodeUtil.generateLarkCode(uid));
            u.setId(uid);
            userMapper.updateByPrimaryKeySelective(u);
            Map<String,Integer> map = new HashMap   ();
            map.put("currentUid",uid);
            userToCService.initUserInfo(map);
            user = getUserToDbByUid(uid);
            //暂时不统计有米渠道信息
//            threadPool.execute(new Runnable() {
//                @Override
//                public void run() {
//                    youmiChannelPush(idfa,phone,uid);
//                }
//            });
        } else {
            return null;
        }
        return user;
    }

    /**
     * 公共cookies生成
     * @param userCookiesName 用户cookies
     * @param uid 用户ID
     * @return 用户cookies名称
     */
    public String commonCookies(String userCookiesName,Integer uid,String appid){
        String cookies;
        AppUserCacheInfo appUserCacheInfo;
        if (StringUtils.isBlank(userCookiesName)) {
            appUserCacheInfo = new AppUserCacheInfo();
            appUserCacheInfo.setUser_id(uid);
            appUserCacheInfo.setUpdate_time(DateUtils.getSecondTimestampOne(new Date()));
            appUserCacheInfo.setAppid(appid);
            cookies = DataEncryptionUtils.SHA1(appUserCacheInfo.toString());
        } else {
            cookies = userCookiesName;
            RedisKey redisKey = new RedisKey("",cookies);
            try {
                appUserCacheInfo = (AppUserCacheInfo) myRedisTemplate.getObjectFromC(redisKey, AppUserCacheInfo.class);
                if (appUserCacheInfo != null) {
                    appUserCacheInfo.setUser_id(uid);
                    appUserCacheInfo.setUpdate_time(DateUtils.getSecondTimestampOne(new Date()));
                } else {
                    appUserCacheInfo = new AppUserCacheInfo();
                    appUserCacheInfo.setUser_id(uid);
                    appUserCacheInfo.setUpdate_time(DateUtils.getSecondTimestampOne(new Date()));
                    appUserCacheInfo.setAppid(appid);
                }
            } catch (UnsupportedEncodingException e) {
                logger.error("获取用户cookies失败：uid为：【{}】；userCookiesName为：{}；异常信息为：{}",uid,userCookiesName,e);
                appUserCacheInfo = new AppUserCacheInfo();
                appUserCacheInfo.setUser_id(uid);
                appUserCacheInfo.setUpdate_time(DateUtils.getSecondTimestampOne(new Date()));
                appUserCacheInfo.setAppid(appid);
            }
        }

        myRedisTemplate.setJsonToRedis(cookies,GsonUtils.toJson(appUserCacheInfo));
        return cookies;
    }

    /**
     * 更新用户设备及推送信息
     * @param devToken 设备信息
     * @param clientId  个推ID
     * @param uid   用户ID
     */
    public void updateLoginInfo(String devToken,String clientId,int uid){
        //更新用户登陆信息
        TbUser u = new TbUser();
        u.setId(uid);
        u.setDeviceToken(devToken);
        u.setGetuiId(clientId);
        u.setLoginTime(new Date());
        userMapper.updateByPrimaryKeySelective(u);
    }



    private void youmiChannelPush( String idfa, String phone, int uid){
        TbAppPromotionChannelExample example = new TbAppPromotionChannelExample();
        TbAppPromotionChannelExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        criteria.andIfaEqualTo(idfa);
        criteria.andIsActivationEqualTo(Constants.BYTE_ZERO);
        List<TbAppPromotionChannel> appPromotionChannelList = appPromotionChannelMapper.selectByExample(example);
        if (appPromotionChannelList != null && appPromotionChannelList.size() > 0) {
            TbAppPromotionChannel appPromotionChannel = appPromotionChannelList.get(0);
            String callbackUrl = appPromotionChannel.getCallbackUrl();
            String result = "";
            try {
                result = HttpClientUtils.get(Coder.urlDecoder(callbackUrl));
                logger.info("result:{}", result);
                YoumiResult youmiResult = GsonUtils.jsonStrToEntity(result,YoumiResult.class);
                if (youmiResult.getC() == 0) {
                    appPromotionChannel.setActivationPhone(phone);
                    appPromotionChannel.setActivationTime(new Date());
                    appPromotionChannel.setActivationUid(uid);
                    appPromotionChannel.setIsActivation(Constants.BYTE_ONE);
                    appPromotionChannelMapper.updateByPrimaryKeySelective(appPromotionChannel);
                }
            } catch (Exception e) {
                logger.error("有米推广渠道回调失败：失败ifa：{}，失败时间：{}，调用返回值：{}，失败手机号：{}，异常信息：{}",idfa, DateUtils.getStandardCurrentTime(),result,phone,e);
            }
        }
    }

}
